import cv2
import numpy as np
# 读取图像
img = cv2.imread('./images/Peppers.png')
# 转换为LAB颜色空间
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
# 分离L、A、B通道
l_channel, a_channel, b_channel = cv2.split(lab)
# 使用Otsu阈值法进行二值化
ret, binary = cv2.threshold(l_channel, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# 进行形态学处理，去除噪声
kernel = np.ones((5,5), np.uint8)
opening = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)
# 寻找轮廓
contours, hierarchy = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 绘制区域
mask = np.zeros(img.shape[:2], dtype=np.uint8)
for i in range(len(contours)):
    cv2.drawContours(mask, contours, i, 255, -1)
# 在原图像上进行区域分割
result = cv2.bitwise_and(img, img, mask=mask)

# 显示分割结果
cv2.imshow('region', result)
cv2.waitKey(0)
cv2.destroyAllWindows()